package com.hui.service;

import com.hui.dao.ClassDao;
import com.hui.dao.StudentDao;
import com.hui.entity.Student;
import com.hui.service.StudentService;
import com.hui.util.DaoFactory;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/06/19/16:00
 * @Description:
 */
public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao = DaoFactory.getStudentDao();
    private ClassDao classDao = DaoFactory.getClassDao();
    private static final int pageSize = 6;

    @Override
    public int getTotalPage() {
        int count = studentDao.getCount();
        int totalPage = count / pageSize;
        if (count % 6 != 0) {
            totalPage++;
        }
        return totalPage;
    }

    @Override
    public List<Student> getPageStudent(int page) {
        int start = (page - 1) * pageSize;
        return studentDao.getPageStudent(start, pageSize);
    }

    @Override
    public List<Student> getStudentById(int id) {
        return studentDao.getStudentById(id);
    }

    @Override
    public List<Student> getStudentByClassId(int classId) {
        return studentDao.getStudentByClassId(classId);
    }


    @Override
    public boolean deleteStudentById(int id, int classId) {
        boolean b = studentDao.deleteStudentById(id);
        // 删除成功后，将所在的班级人数-1
        if (b) {
            // 通过学号获取所在的班级编号
            classDao.minusOne(classId);
        }
        return b;
    }

    @Override
    public boolean updateStudent(Student student) {
        // 如果修改的班级编号不存在，直接返回false
        if(!classDao.exitClass(student.getClassId())){
            return false;
        }
        // 根据用户id获取原先的班级编号
        int oldClassId = studentDao.getStudentById(student.getId()).get(0).getClassId();
        // 修改用户
        boolean b = studentDao.updateStudent(student);
        // 获取修改后的班级编号
        int newClassId = student.getClassId();
        // 如果修改成功原先班级人数-1，现在班级人数+1
        if (b) {
            classDao.minusOne(oldClassId);
            classDao.plusOne(newClassId);
        }
        return b;
    }

    @Override
    public boolean insertStudent(Student student) {
        if(!classDao.exitClass(student.getClassId())){
            return false;
        }
        boolean b = studentDao.insertStudent(student);
        // 添加成功后，将所在的班级人数+1
        if (b) {
            classDao.plusOne(student.getClassId());
        }
        return b;
    }
}
